package com.controller;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.validation.Valid;

import com.sound.common.MyValidationUtils;
import com.sound.common.Response;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import com.service.AlbumService;
import com.service.AudioService;
import com.sound.model.AlbumModel;
import com.sound.model.AudioModel;
import com.sound.model.CollectModel;
import com.sound.vo.CollectVo;

@RestController
@Api(tags="收藏")
@RequestMapping(path = "/collect")
public class CollectController extends BaseController<CollectModel> {

	@Autowired
	private AlbumService albumService;

	@Autowired
	private AudioService audioService;

	/**
	 * 如果是正常的bigType就传bigType 如果是音频,bigType就传0
	 * 
	 */
	@GetMapping(path = "/save")
	@ResponseBody
	@Override
	public Response<Void> save(@ModelAttribute @Valid CollectModel t, BindingResult result) {
		return super.save(t, result);
	}

	@GetMapping(path = "/findByExample")
	public Response<CollectVo> findBy(@Valid CollectModel ex, BindingResult result) {
		if(result.hasErrors()) {
			return new Response<CollectVo>(false,MyValidationUtils.parseErrors(result));
		}
		Example<CollectModel> example = Example.of(ex);
		Iterable<CollectModel> modelIterable = service.findAll(example);
		Iterator<CollectModel> modelIterator = modelIterable.iterator();
		List<CollectVo> listVo = new ArrayList<CollectVo>();
		Response<CollectVo> resp = new Response<CollectVo>();
		if(ex.getIsAlbum()) {
			List<Long> albumIds = new ArrayList<Long>();
			while (modelIterator.hasNext()) {
				CollectModel cm = modelIterator.next();
				albumIds.add(cm.getId());
			}
			Iterable<AlbumModel> albums = albumService.findAllById(albumIds);
			CollectVo<AlbumModel> collectVo = new CollectVo<AlbumModel>();
			collectVo.setList(albums);
			resp.setData(collectVo);
		}else {
			List<Long> audioIds = new ArrayList<Long>();
			while (modelIterator.hasNext()) {
				CollectModel cm = modelIterator.next();
				audioIds.add(cm.getId());
			}
			Iterable<AudioModel> audios =  audioService.findAllById(audioIds);
			CollectVo<AudioModel> collectVo = new CollectVo<AudioModel>();
			collectVo.setList(audios);
			resp.setData(collectVo);
		}
		
		return resp;
	}

	@GetMapping(path = "/deleteById")
	@Override
	public Response<Void> deleteById(Long id) {
		// TODO Auto-generated method stub
		return super.deleteById(id);
	}

}
